import Request from 'utils/request';
import SystemUtil from 'utils/systemUtil';

import GoodsForm from 'models/goods/goodsForm';
import GoodsModelForm from 'models/goods/goodsModelForm';
import ActivityTypeForm from 'models/goods/activityTypeForm';
import GoodsActivityForm from 'models/goods/goodsActivityForm';

const getImgSize = image => {
  return new Promise((resolve, reject) => {
    let fileData = {
      id: image.id,
      url: image.url
    };
    let imgDom = new Image();
    imgDom.src = image.url;
    imgDom.onload = function () {
      fileData.width = imgDom.width;
      fileData.height = imgDom.height;
      resolve(fileData);
    }

    imgDom.onerror = function (error) {
      reject(error);
    }
  });
};

export default class GoodsApi {
  static getGoodsList(search, pagination, user) {
    const apiName = 'api/goodsdef/list';

    let postData = search.getObject(pagination);
    let partnerId = user.partnerId;
    if (!SystemUtil.isEmpty(partnerId)) {
      postData.partnerId = partnerId;
    } else {
      postData.branchId = user.branchId;
    }

    return Request.post(apiName, postData).then(res => {
      let goodsList = res.data;
      goodsList = _.map(goodsList, goods => {
        goods = new GoodsForm(goods, undefined, 'table');
        return goods;
      });

      pagination.totalCount = res.rows;
      return goodsList;
    });
  }

  static getGoodsModelList(goodsForm) {
    const apiName = 'api/goodsmodel/all';
    return Request.post(apiName, {
      goodsDefId: goodsForm.id
    }).then(res => {
      let goodsModelList = res.data;
      goodsModelList = _.map(goodsModelList, goodsModel => {
        goodsModel = new GoodsModelForm(goodsModel);
        return goodsModel;
      })
      return goodsModelList;
    });
  }

  static getGoodsMajorType(goodsForm) {
    const apiName = 'api/goodsdef/getGoodsTypeInStore';

    let typeList = null;
    if (goodsForm !== undefined) {
      typeList = goodsForm.majorType;
    }

    return Request.post(apiName).then(res => {
      let majorTypeList = res.data;
      let majorTypes = [];
      let ids = [];
      for (let i = 0; i < majorTypeList.length; i++) {
        let major = majorTypeList[i];
        let majorTypeId = major.majorTypeId;
        ids.push(majorTypeId);
        majorTypes.push({
          id: majorTypeId,
          name: major.majorName,
          disabled: false
        });
      }

      if (!SystemUtil.isEmpty(typeList)) {
        let nameList = goodsForm.majorTypeName;
        let addList = [];
        for (let i = 0; i < typeList.length; i++) {
          let type = typeList[i];
          if (ids.indexOf(type) === -1) {
            addList.push({
              id: type,
              name: nameList[i],
              disabled: true
            });
          }
        }
        if (addList.length > 0) {
          majorTypes = [...addList, ...majorTypes]
        }
      }

      return majorTypes;
    });
  }

  static addGoods(goodsForm) {
    const apiName = 'api/goodsdef/save';
    let postData = goodsForm.getObject(false, true);

    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static updateGoods(goodsForm) {
    const apiName = 'api/goodsdef/update';
    let postData = goodsForm.getObject();

    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static delGoods(goodsDefId) {
    const apiName = 'api/goodsdef/delete';
    return Request.post(apiName, {
      goodsDefId
    }).then(res => {
      return res.msg;
    });
  }

  static createNewGoods(goodsForm) {
    const apiName = 'api/goodsdef/save';
    let postData = goodsForm.getObject(true, true);
    return Request.post(apiName, postData).then(res => {
      let goodsDefId = res.data;
      return this.addGoodsModelList(goodsForm, goodsDefId).then(msg => {
        return msg;
      });
    });
  }

  static updateGoodsStatus(goodsDefId, status, option) {
    let postData = {
      goodsDefId,
      status
    };

    if (option !== undefined) {
      let timeData = option.timeData;
      if (timeData !== undefined) {
        postData.verifiedApplyActivityStartTime = timeData.startTime;
        postData.verifiedApplyActivityEndTime = timeData.endTime;
      }
      let reasonText = option.reasonText;
      if (reasonText !== undefined) {
        postData.auditMsg = reasonText;
      }
    }

    const apiName = 'api/goodsdef/updateStatusById';
    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static addGoodsModelList(goodsForm, goodsDefId) {
    const apiName = 'api/goodsmodel/listSave';
    let postData = goodsForm.getModelList(goodsDefId);

    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static addGoodsModel(goodsModelForm, goodsDefId) {
    const apiName = 'api/goodsmodel/save';
    let postData = goodsModelForm.getObject(goodsDefId);
    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static updateGoodsModel(goodsModelForm) {
    const apiName = 'api/goodsmodel/update';
    let postData = goodsModelForm.getObject();
    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static delGoodsModel(id) {
    const apiName = 'api/goodsmodel/delete';
    return Request.post(apiName, {
      goodsModelId: id
    }).then(res => {
      return res.msg;
    });
  }

  static getApprovalGoodsList(search, pagination) {
    const apiName = 'api/goodsdef/verifyList';
    let postData = search.getObject(pagination, 'approval');

    return Request.post(apiName, postData).then(res => {
      let goodsList = res.data;
      goodsList = _.map(goodsList, goods => {
        goods = new GoodsForm(goods, undefined, 'approval');
        return goods;
      });

      pagination.totalCount = res.rows;
      return goodsList;
    });
  }

  static getActivityList(search, pagination) {
    const apiName = 'api/activitytype/list';
    let postData = search.getObject(pagination);
    return Request.post(apiName, postData).then(res => {
      let activityList = res.data;
      activityList = _.map(activityList, activity => {
        activity = new ActivityTypeForm(activity);
        return activity;
      });

      pagination.totalCount = res.rows;
      return activityList;
    });
  }

  static addActivity(activityTypeForm) {
    const apiName = 'api/activitytype/save';
    let postData = activityTypeForm.getObject();
    return Request.post(apiName, postData).then(res => {
      return res.data;
    });
  }

  static updateActivity(activityTypeForm) {
    const apiName = 'api/activitytype/update';
    let postData = activityTypeForm.getObject();
    return Request.post(apiName, postData).then(res => {
      return res.data;
    });
  }

  static getGoodsActivityList(search, pagination) {
    const apiName = 'api/activitygoods/list';
    let postData = search.getObject(pagination);
    return Request.post(apiName, postData).then(res => {
      let activityList = res.data;
      activityList = _.map(activityList, activity => {
        activity = new GoodsActivityForm(activity);
        return activity;
      });

      pagination.totalCount = res.rows;
      return activityList;
    });
  }

  static addGoodsActivity(activityForm) {
    const apiName = 'api/activitygoods/save';
    let postData = activityForm.getObject();
    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static updateGoodsActivityStatus(activityForm, status) {
    const apiName = 'api/activitygoods/update';
    let postData = activityForm.getObject();
    postData.status = status;
    return Request.post(apiName, postData).then(res => {
      return res.msg;
    });
  }

  static getGoodsDropdown(activityForm, type) {
    let branchId = activityForm.branchId;
    if (branchId === '') {
      return Promise.resolve([]);
    }

    const apiName = 'api/goodsdef/all';
    let postData = {
      status: 1,
      branchId
    };

    if (type === 'partner') {
      let partnerId = activityForm.partnerId;
      if (partnerId !== '') {
        postData.partnerId = partnerId;
      }
    }

    return Request.post(apiName, postData).then(res => {
      let goodsList = res.data;
      goodsList = _.map(goodsList, goods => {
        return {
          id: goods.goodsDefId,
          name: goods.goodsName
        };
      });
      return goodsList;
    });
  }

  static getGoodsNameDropdown(search) {
    let branchId = search.branchId;
    if (branchId === '') {
      return Promise.resolve([]);
    }

    const apiName = 'api/goodsdef/all';
    let postData = {
      branchId
    };

    let partnerId = search.partnerId;
    if (partnerId !== '') {
      postData.partnerId = partnerId;
    }

    return Request.post(apiName, postData).then(res => {
      let goodsList = res.data;
      goodsList = _.map(goodsList, 'goodsName');
      goodsList = _.uniq(goodsList);
      return goodsList;
    });
  }

  static getActivityDropdown() {
    const apiName = 'api/activitytype/all';
    return Request.post(apiName).then(res => {
      let activityList = res.data;
      let activitys = [];
      for (let i = 0; i < activityList.length; i++) {
        const activity = activityList[i];
        let status = activity.status;
        if (status === '0') {
          continue;
        }
        activitys.push({
          id: activity.activityTypeId,
          name: activity.activityTypeName
        });
      }
      return activitys;
    });
  }

  static getGoodsImage(goodsName) {
    const apiName = 'api/taobaoke/getImageByGoodsName';
    return Request.post(apiName, {
      goodsName
    }).then(res => {
      let imgList = res.data;
      imgList = _.map(imgList, url => {
        return {
          id: SystemUtil.getId(),
          checked: false,
          url
        }
      });
      return imgList;
    });
  }

  static async uploadGoodsImgList(imageList) {
    imageList = _.map(imageList, image => {
      return {
        id: image.id,
        url: image.url
      };
    });
    imageList = await this.uploadImageList(imageList);
    if (_.isError(imageList)) {
      return Promise.reject(imageList);
    }
    let imgPromiseList = [];
    for (let i = 0; i < imageList.length; i++) {
      const image = imageList[i];
      imgPromiseList.push(getImgSize(image));
    }

    return Promise.all(imgPromiseList).then(imgDataList => {
      return imgDataList;
    });
  }

  static uploadImageList(imageList) {
    const apiName = 'api/qiniu/imgUrluploadFile';
    return Request.post(apiName, {
      urls: imageList
    }).then(res => {
      return res.data;
    }).catch(error => {
      return error
    });
  }
}
